package com.offcn.gatewabweb.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;



/**
 * 授权过滤器
 *
 * @author 秋林
 * @date 2022/10/13 15:20:50
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 令牌头名
     */
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 用户登录网址
     */
    private static final String User_LOGIN_URL = "http://localhost:9100/oauth/login";

    /**
     * 过滤器
     * 全局过滤器
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@link Mono}<{@link Void}>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求的URI
        String path = request.getURI().getPath();
        System.out.println("获取请求的URI: " + path);

        if(URLFilter.hasAuthorize(path)){
            //放行
            return chain.filter(exchange);
        }

        //获取头文件中的令牌信息
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);

        //如果头文件中没有，则从请求参数中获取
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }

        //header没有令牌，从cookie中获取令牌数据
        if (StringUtils.isEmpty(token)) {
            HttpCookie first = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (first != null) {
                token=first.getValue();
            }
        }

        if (StringUtils.isEmpty(token)) {
            //未登录跳转到登录页面
            String uri = request.getURI().toString();
            return needAuthorization(User_LOGIN_URL, exchange, uri);
        }

        //判断是否有bearer前缀
        if (!token.startsWith("bearer ")&&!token.startsWith("Bearer ")){
            token = "bearer "+token;
        }
        System.out.println(token);

        request.mutate().header(AUTHORIZE_TOKEN, token);
        //放行
        return chain.filter(exchange);
    }

    /**
     *
     * 过滤器执行器
     *
     * @return int
     */
    @Override
    public int getOrder() {
        return 0;
    }


    /**
     * 响应头
     *
     * @param url      url
     * @param exchange 交换
     * @param from     从
     * @return {@link Mono}<{@link Void}>
     */
    private  Mono<Void> needAuthorization(String url, ServerWebExchange exchange, String from) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        // url - 跳转的登录模块地址
        // from - 将跳转前的地址记录, 方便登录成功后再自动跳回来
        response.getHeaders().set("Location",url+"?from="+from);
        return exchange.getResponse().setComplete();
    }
}